<template>
  <view class="cp-page">
    <view class="list">
      <view class="cell">
        <text class="label">我的密码</text>
        <input class="ipt" type="password" placeholder="请输入原密码" v-model="form.old" />
      </view>
      <view class="cell">
        <text class="label">设置新密码</text>
        <input class="ipt" type="password" placeholder="请输入新密码" v-model="form.new1" />
      </view>
      <view class="cell">
        <text class="label">确认新密码</text>
        <input class="ipt" type="password" placeholder="请再次输入新密码" v-model="form.new2" />
      </view>
    </view>

    <button class="submit" @click="submit" :loading="loading">确定</button>
  </view>
</template>

<script>
import { updateUserPwd } from '@/api/system/user'

export default {
  data() {
    return {
      form: { old: '', new1: '', new2: '' },
      loading: false
    }
  },
  methods: {
    async submit() {
      // 前置清理与校验
      this.form.old = (this.form.old || '').trim()
      this.form.new1 = (this.form.new1 || '').trim()
      this.form.new2 = (this.form.new2 || '').trim()
      if (!this.form.old || !this.form.new1 || !this.form.new2) {
        return this.$modal.msg('请完整填写密码')
      }
      if (this.form.new1.length < 6) {
        return this.$modal.msg('新密码长度不能少于6位')
      }
      if (this.form.old === this.form.new1) {
        return this.$modal.msg('新密码不能与原密码相同')
      }
      if (this.form.new1 !== this.form.new2) {
        return this.$modal.msg('两次新密码不一致')
      }
      try {
        this.loading = true
        await updateUserPwd(this.form.old, this.form.new1)
        this.$modal.msgSuccess('密码已修改，请重新登录')
        await this.$store.dispatch('LogOut')
        uni.reLaunch({ url: '/pages/login' })
      } catch (e) {
        console.error('change password failed', e)
        const msg = (e && (e.msg || e.message)) || (e && e.data && (e.data.msg || e.data.message)) || '修改失败'
        this.$modal.msg(msg)
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.cp-page { background: #f5f5f5; min-height: 100vh; padding-top: 20rpx; }
.list { background: #fff; }
.cell {
  padding: 26rpx 30rpx; border-bottom: 1rpx solid #f0f0f0; display: flex; align-items: center;
  .label { width: 220rpx; color: #333; font-size: 30rpx; }
  .ipt { flex: 1; text-align: right; font-size: 28rpx; color: #666; }
}
.submit { width: 690rpx; margin: 60rpx auto 0; background: #1677ff; color: #fff; }
</style>
